/**
 * @作者 YuKok
 * @创建时间 2020/5/13 16:36
 */
package com.lucas.springboot_restful_api.util;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.stream.Stream;

@Component
public class HttpClient {

    static RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public static ResponseEntity<String> get(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(headers);
        return restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    }

    public static ResponseEntity<String> post(String url, Map<String, Object> params) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(params, headers);
        return restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
    }

    public static Cookie[] getCookies(HttpServletRequest request) {
        return request.getCookies();
    }

    public static Boolean hasCookies(HttpServletRequest request) {
        return ! (request.getCookies().length == 0);
    }

    public static String getCookie(String key, HttpServletRequest request) {
        if (!HttpClient.hasCookies(request)) {
            return null;
        }
        if (HttpClient.hasCookie(key,request)) {
            for (int i = 0; i < HttpClient.getCookies(request).length; i++) {
                if (HttpClient.getCookies(request)[i].getName().equals(key)) {
                    return HttpClient.getCookies(request)[i].getValue();
                }
            }
        }
        return null;
    }

    public static Boolean hasCookie(String key, HttpServletRequest request) {
        if (!HttpClient.hasCookies(request)) {
            return false;
        }
        for (Cookie cookie : HttpClient.getCookies(request)) {
            if (cookie.getName().equals(key)) {
                return true;
            }
        }
        return false;
    }

    public static String getCookieAtFirst(HttpServletRequest request) {
        if (!HttpClient.hasCookies(request)) {
            return null;
        }
        return HttpClient.getCookies(request)[0].getValue();
    }

}
